from django.shortcuts import render
from rest_framework.views import APIView
from .models import Teacher,Stutend
from rest_framework.response import Response
from .serializer import TeacherSer,StutendSer
# Create your views here.

# 获取所有的老师
class GetTeacher(APIView):
    def get(self,request):
        data = Teacher.objects.all()
        ser_data = TeacherSer(data,many=True)
        return Response({
            "code":200,
            "msg":"查询成功",
            "data":ser_data.data
        })

# 根据老师获取学生
class GetStutend(APIView):
    def get(self,request,id):
        tea = Teacher.objects.get(id=id)
        stu = tea.stutend_set.all()
        ser = StutendSer(stu,many=True)
        return Response({
            "code":200,
            "msg":"获取成功",
            "data":ser.data
        })

# 添加学生
class AddStutend(APIView):
    def post(self,request):
        sname = request.data.get("sname")
        tid = request.data.get("tid")
        img = request.data.get("img")

        try:
            data = Teacher.objects.get(id=tid)
        except Exception as e:
            return Response("没有这个老师")

        try:
            Stutend.objects.create(sname=sname,img=img,tid_id=tid)
            return Response({
                "code":200,
                "msg":"添加成功"
            })
        except Exception as e:
            print("添加失败的原因是>>>>>",e)
            return Response("添加失败")

# 删除
class DeStudent(APIView):
    def delete(self,request,id):
        try:
            Stutend.objects.filter(id=id).delete()
            return Response({
                "code":200,
                "msg":"删除成功"
            })
        except Exception as e:
            print("删除失败的原因是>>>>",e)
            return Response("删除成功")

    # 修改
    def put(self, request):
        id = request.data.get('tid')
        sname = request.data.get("sname")
        img = request.data.get('img')
        try:
            Stutend.objects.filter(id=id).update(
                sname=sname,
                tid_id=id,
                img=img,
            )
            return Response({
                'code': 200,
                'msg': '修改成功'
            })
        except Exception as e:
            print('>>>>>更失败原因', e)


